#include "WijiUi.h"
#include <QtGui/QMainWindow>
#include <QtWebKit>
#include <QAction>
#include <QtDebug>
#include <QDialog>
#include "passdialog.h"
#include "scripter.h"
#include <QMessageBox>
#include <QWebElement>
#include "WijiSettings.h"
#include "wijiuiscriptable.h"

WijiUi* WijiUi::_self = NULL;
WijiUi::WijiUi(QMainWindow *parent) {
}
void WijiUi::init(QMainWindow *parent = 0) {
    if (!_self) {
        _self = new WijiUi();
     }
    _self->parentObject = parent;
    qDebug() << "Initializing";
    WijiSettings* ws = WijiSettings::getSelf();
   //_self->scripter.engine.
    _self->parentObject->resize(
            QSize(
                  ws->getValue("width").toInt(),
                  ws->getValue("height").toInt()
                   )
            );
     _self->webView = new QWebView(_self->parentObject);
     _self->webView->resize(
           ws->getValue("width").toInt(),
           ws->getValue("height").toInt()
            );
    QWebSettings *defaultSettings = QWebSettings::globalSettings();
    defaultSettings->setAttribute(QWebSettings::PluginsEnabled, true);
    //Start the RPC server...why here? Ehh...there were issues...

    _self->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    _self->parentObject->setCentralWidget(_self->webView);
    _self->connectSlots();
    _self->runInitScripts();
    _self->rpc.init();

    //scripter.execPython(QString("application/index.py"));
}
void WijiUi::afterShow() {
    _self->linkClicked(
                            QUrl(
                                    WijiSettings::getSelf()->getValue("index_file").toString()
                                 )
                          );
}
void WijiUi::setWindowSize(int width, int height) {
    _self->parentObject->resize(
            QSize(
                   width,
                   height
                   )
            );
    _self->webView->resize(
           width,
           height
           );
}
void WijiUi::connectSlots() {
    connect(_self->webView->page()->currentFrame(), SIGNAL(loadFinished(bool)), _self,SLOT(finishLoading(bool)));
    connect(_self->webView->page(), SIGNAL(windowCloseRequested()),_self, SLOT(windowCloseRequested()));
    connect(_self->webView->page(),SIGNAL(linkClicked(QUrl)),_self,SLOT(linkClicked(QUrl)));
    connect(_self->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), _self,SLOT(addJavascriptObjects()));
}
void WijiUi::addJavascriptObjects() {
    qDebug() << "Adding JS Object";
    _self->webView->page()->mainFrame()->addToJavaScriptWindowObject("wiji",
                                                  WijiUiScriptable::getSelf());
}
void WijiUi::linkClicked(QUrl url) {
    qDebug() << "Link Clicked: " << url.toString();
    QScriptValue global = scripter.engine.globalObject();
    if (!global.property(QLatin1String("REQUEST")).isValid()) {
        global.setProperty(QLatin1String("REQUEST"), url.toString());
    } else {
        global.setProperty(QLatin1String("REQUEST"), url.toString());
    }
    scripter.runQtScript(WijiSettings::getSelf()->getValue("system_scripts").toString() + "/router.qs"); //i.e. we let the router handle everything...easier that way.
}
void WijiUi::runInitScripts() {
    WijiSettings* ws = WijiSettings::getSelf();
    _self->scripter.init();
    _self->thisObject = _self->scripter.engine.newQObject(_self);
    //Run the main init.qs script
    if (ws->getValue("init_script").toBool() != false) {
        _self->scripter.runQtScript(ws->getValue("init_script").toString());
    } // if ws->getValue init_script
}

void WijiUi::finishLoading(bool)
{
    progress = 100;
    qDebug() << "Loading complete...";
    QFile file;
    file.setFileName(":/jquery.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    file.close();
    _self->webView->page()->mainFrame()->evaluateJavaScript(jQuery);
    //_self->parseDocument();
}


void WijiUi::windowCloseRequested(){
    if (WijiSettings::getSelf()->getValue("kiosk").toBool() == true) {
        PassDialog d(_self->parentObject);
        if (d.exec() == QDialog::Accepted) {
            if (d.checkPass() == true) {
                parentObject->close();
            } else {
                qDebug() << "Pass did not match!";
            }
        }
        //close();
    } else {
        parentObject->close();
    }
}
//Functions meant to be accessed via Qt Script
void WijiUi::notify(QString title,QString msg) {
    //This function will eventually be replaced by a mini-wiji window with a mini webview called WijiDialog
    QMessageBox::about(0,title,msg);
}
void WijiUi::redirectTo(QString url) {
    _self->webView->load(QUrl(url));
}
void WijiUi::closeAll(){
    parentObject->close();
}
void WijiUi::consoleLog(QString text) {
    qDebug() << text;
}

bool WijiUi::setContentOf(QString id,QString html) {
    QWebElement e =_self->webView->page()->currentFrame()->findFirstElement(id);
    if (! e.isNull()) {
        e.setInnerXml(html);
        return true;
    }
    qDebug() << "Nope, item was null";
    return false;
}
bool WijiUi::replaceWith(QString id,QString html) {
    QWebElement e =_self->webView->page()->currentFrame()->findFirstElement(id);
    if (e.isNull()) {
        e.setOuterXml(html);
        return true;
    }

    return false;
}
void WijiUi::setHtml(QString contents, QString url) {
    webView->setHtml(contents,QUrl(url));
}
